<template>
    <div>
        <el-form :model="yunjiForm" ref="formDataForm" :inline="true" class="search-form-new" label-width="68px">
            <el-form-item label="">
                <el-select ref="remoteSelect" v-model="selectId" clearable filterable remote reserve-keyword placeholder="请输入账号"
                    :remote-method="remoteMethod" :loading="loading2">
                    <el-option v-for="item in options" :key="item.id" :label="item.account" :value="item.id">
                        <div class="option-content" :class="{ 'option-content-error': item.onlineStatus == 3 }">
                            <!-- 主信息：账号 + QQ -->
                            <el-tag v-if="item.onlineStatus != 3"
                                :type="item.onlineStatus === 2 ? 'success' : 'warning'" size="small">
                                {{ item.onlineStatus === 2 ? '登录' : '未登录' }}
                            </el-tag>
                            <el-tag v-else type="danger" size="small">异常</el-tag>

                            <div class="main-info margin-left-5">
                                <span class="account">{{ item.account }}</span>
                                <el-tag size="mini margin-left-5">{{ item.loginType == 2 ? 'QQ' : 'TIM' }}</el-tag>
                            </div>
                            <div class="main-info margin-left-5">
                                <el-tag size="mini margin-left-5">{{ item.machineType == 2 ? '平板' : '手机' }}</el-tag>
                            </div>
                            <div class="sub-info">
                                <el-tag size="mini" class="margin-left-5">已登录{{ getDay(item.loginTime) }} </el-tag>
                                <el-tag size="mini" class="margin-left-5">距创建{{ getDay(item.createDays) }} </el-tag>
                                <span class="created margin-left-5">创建: {{ item.createdTime }}</span>
                            </div>
                        </div>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-button type="primary" :loading="loading3" size="small" @click="openAccountUrl">
                打开查看账号
            </el-button>
            <el-form-item label="" prop="account" class="margin-left-10">
                <el-input v-model="yunjiForm.account" placeholder="请创建账号" clearable size="small" />
            </el-form-item>
            <el-button type="primary" size="small" :loading="loading1" @click="accountCreate">
                创建账号
            </el-button>
            <!-- <el-button type="warning" icon="el-icon-refresh" size="small" @click="fresh">
                刷新
            </el-button> -->
            <el-radio-group v-model="yunjiForm.loginType" class="margin-left-10">
                 <el-radio :label="2">QQ</el-radio>
                <el-radio :label="1">TIM</el-radio>
               
            </el-radio-group>
            <el-radio-group v-model="yunjiForm.machineType" style="margin-left: 20px;">
                <el-radio :label="1">手机</el-radio>
                <el-radio :label="2">平板</el-radio>
            </el-radio-group>

        </el-form>
        <!-- 多个云机实例容器 -->
        <div class="grid-container">
            <!-- 渲染多个云机实例 -->
            <div v-for="(tenant, index) in yunjiTable" :key="tenant.id || index" class="grid-box">
                <!-- 隐藏的粘贴输入框，用于捕获粘贴事件 -->
             
                <div class="grid-content bg-purple-light">
                       <input v-if="tenant.wss_url" ref="pasteInput" class="paste-input" @paste="handlePaste(index, $event)"
                    @drop="onScanDrop(index, $event)" placeholder="点击此处粘贴图片进行扫码" />
                    <!-- 提示信息 -->
                    <el-popover placement="right" width="420" trigger="click">
                        <div class="flex-r-tips flex"><div>1、</div>
                        <div> 注意:您要登录的账号为 <span class="accounts">{{ tenant.account}}</span>,
                            请不要登录其他账号,否则系统将无法准确记录账号状态
                            </div>
                        </div>
                        <div class="flex-r-tips" style="display: flex;">
                            <div>2、</div>
                            <div>登录完成后请点击下方确认登录按钮,否则将不会自动挂机</div>
                        </div>
                        <div class="flex-r-tips flex" style="font-size: 14px;">
                            <div>3、</div>
                            若超时间未操作,云控可能卡死,请关闭重试</div>
                        <i v-if="tenant.account && tenant.wss_url" slot="reference" class="el-icon-question"></i>
                    </el-popover>

                    <!-- 账号信息显示 -->
                    <div @click="copyAccount(tenant)" class="account-tips" v-if="tenant.account && tenant.wss_url">
                        {{ tenant.account }}
                    </div>

                    <!-- 云机iframe -->
                    <yunjiIframe :ref="`yunjiIframeRef_${index}`" v-if="tenant.wss_url" :wssUrl="tenant.wss_url"
                        :accountId="tenant.accountId" @reconts="reconts(tenant, index)" @activateComponent="activateComponent(tenant,index)">
                    </yunjiIframe>

                    <!-- 空状态 -->
                    <div class="flex flex-l" v-else>
                        <div class="flex-item">
                            <img class="yunji-img" src="@/assets/images/yunji.png" alt="">
                        </div>
                        <el-button type="primary" class="add-btn" @click="openRentDialog">新增云控制</el-button>
                    </div>


                    <!-- 操作按钮 -->
                    <div class="flex-footer" v-if="tenant.wss_url">
                        <div class="flex flexc">
                            <el-button type="primary" plain @click="handleSubmit(tenant, index)">确认登录</el-button>
                            <el-button type="danger" class="margin-left-10" plain
                                @click="loginErrSure(tenant, index)">登录失败</el-button>
                                <el-button type="info" class="margin-left-10" plain
                                @click="closeYunji(tenant, index)">关闭</el-button>
                            <el-popover placement="top-start" width="100" trigger="click">
                                <div class="tips">
                                        <div type="info"
                                @click="deleteSure(tenant, index)">删除</div>
                                    <div @click="takeAndDownloadScreenshot('jietu', index)">截图</div>
                                    <div @click="scanClick('scanAuto', index)">
                                        扫码上号(自动)</div>
                                    <div @click="openUploadQr(index)">上传图片(扫码)</div>
                                </div>
                                <el-button slot="reference" class="margin-left-10">操作</el-button>
                            </el-popover>
                        </div>
                    </div>
                </div>
            </div>
        </div>
          <!--    上传图片弹窗-->
        <el-dialog title="自动上号" :visible.sync="uploadDialog" class="login-dialog" center :auto-upload="false" width="600px">
        <!-- <div :class="{ 'paste-focus': pasteFocus }" class="paste-container" contenteditable="true"
            @blur="pasteFocus = false" @focus="pasteFocus = true" @paste="handlePasteImage">
            <p>在使用微信截图或复制图片后，</p>
            <p>可点击此区域粘贴图片（
            <el-tag style="font-weight: bold;" type="success">Ctrl</el-tag>
            +
            <el-tag style="font-weight: bold;">V</el-tag>
            或
            <el-tag style="font-weight: bold;" type="success">右键</el-tag>
            选择
            <el-tag style="font-weight: bold;">粘贴</el-tag>
            ）
            </p>
        </div> -->
        <div v-if="currentYunji" style="text-align: center;margin-bottom: 10px;">
            当前操作账号： <b style="color: #6C5DD3;font-size: 15px;">{{ currentYunji.account }}</b>
        </div>
        <div contenteditable="true" ref="elUpload" @paste="handlePasteImage" @mouseenter="mouseenter" >
            <el-upload   accept="image/png,image/jpeg,image/jpg" drag class="login-uploader" action="" :show-file-list="false"
            :before-upload="beforeAvatarUpload">
                <div v-if="loginQrCode.imageUrl" class="image-viewer">
                    <img alt="" :src="loginQrCode.imageUrl" class="image-viewer_image">
                </div>
                <div v-else>
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处或粘贴，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过1MB</div>
                </div>
            </el-upload>
        </div>
        
        <span slot="footer" class="dialog-footer">
            <el-button @click="uploadDialog = false">取 消</el-button>
            <el-button type="primary" @click="handleScanLogin">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>
<script>
import { throttle } from 'lodash'; // 引入lodash的节流函数
import { addQ, tenantLists, openAccount, yunjilogin, linkClose, delAccount, getAllList,yunjiClose ,scanCode} from '@/api/tenantApis/cloudMachine'
import { convertImageToPNG } from '../../../../utils/makeImgs-utils/getUrlImg'
export default {
    components: {
        yunjiIframe: () => import('./yunjiIframe.vue'),

    },
    name: "yunji",
    data() {
        return {
            pasteFocus:false,
            loginQrCode:{
                fileSource:'',
                imageUrl:'',
            },
            uploadDialog:false,

            loading: false,
            loading1: false,
            loading2: false,
            loading3: false,
            name: '',
            yunjiForm: {
                account: '',
                loginType: 2,
                machineType: 2
            },
            form: {
                machineId: ''
            },
            // 单个账号相关数据（用于下拉选择）
            wss_url: '',
            sessionId: '',
            id: '',
            dataType: 1,
            loginVisible: false,
            deleteVisible: false,
            openId: '',
            options: [],
            formData: {
                machineAlias: '',
                pageNum: 1,
                pageSize: 9999,
                account: '',
                loginTime: '',
                status: '',
            },
            selectId: '',
            selectObj: { account: '' },
            wssUrlTimer: null,
            throttledRemoteMethod: throttle(this.handleRemoteSearch, 500),

            // 多个云机实例数据
            yunjiTable: [],
            // 每个实例的定时器
            instanceTimers: {},
            // 跟踪正在分配的实例，防止并发问题
            assigningInstances: new Set(),

            // 当前手动扫码的云机信息
             currentYunji:null,
        };
    },
    methods: {
        // 手动扫码上传图片 *******开始********
        // 打开手动扫码上传图片的弹窗
        openUploadQr(index){
            // 获取当前实例信息
            const tenant = this.yunjiTable[index];
            if (!tenant || !tenant.wss_url) {
                this.$message.error('请先连接云控');
                return;
            }

            if (tenant.onlineStatus !== 2) {
                this.$message.warning('账号请先确认登录');
                return;
            }
            this.loginQrCode = {
                fileSource:'',
                imageUrl:'',
            }
            this.currentYunji = {...tenant}
            this.uploadDialog = true 
            // this.$nextTick(()=>{
            //     this.$refs.elUpload.focus()
            // })

        },

        // 开始手动扫码的上传图片
        async handleScanLogin() {
            if (!this.loginQrCode.fileSource) {
                this.$modal.msgError('请先选择图片')
                return
            }
            
            const loginLoading = this.$loading({
                lock: true,
                text: '上传中，请稍等...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)',
            });
           try {
            const pngFile = await convertImageToPNG(this.loginQrCode.fileSource);
            const form = new FormData();
            form.append('file', pngFile);
            form.append('accountId', this.currentYunji.accountId);
            const res = await scanCode(form)
            if (res.code == 200) this.$modal.msgSuccess(`二维码已上传，请打开扫一扫开始操作！`)
            else this.$modal.msgError(`二维码上传出错！`)
           } catch (error) {
            this.$modal.msgError(`二维码上传出错！`)
           }
           this.uploadDialog = false
           this.currentYunji = null
           loginLoading.close()
        },
        mouseenter(){
            this.$refs.elUpload.focus() // 鼠标进入时自动聚焦
        },
        // 手动扫码 弹窗粘贴图片
        handlePasteImage(event) {
            console.log("%c Line:304 🍢 event", "color:#93c0a4", event);
            // 阻止默认粘贴行为（避免粘贴文本到页面）
            event.preventDefault();
            const clipboardData = event.clipboardData || window.clipboardData;
            console.log("%c Line:307 🥥 clipboardData", "color:#42b983", clipboardData);

            const items = clipboardData.items;
            for (let i = 0; i < items.length; i++) {
                const item = items[i];
                // 判断是否为图片类型
                if (item.type.indexOf('image') !== -1) {
                // 获取图片文件对象
                const file = item.getAsFile();
                if (file) {
                    // 将文件转为可预览的 URL（使用 URL.createObjectURL）
                    this.loginQrCode.imageUrl = URL.createObjectURL(file);
                    // 这里可以添加上传图片的逻辑（例如调用接口上传 file 对象）
                    console.log('获取到剪贴板图片：', file);
                    this.loginQrCode.fileSource = file
                    break;
                }
                }
            }
            if (this.loginQrCode.fileSource == null) this.$modal.msgError('请粘贴图片！')

        },
        // 拦截上传方法
        beforeAvatarUpload(file) {
            const isJPG = file.type.indexOf('image');
            const isLt2M = file.size / 1024 / 1024 < 1;

            if (isJPG == -1) {
                this.$message.error('上传文件类型需要为图片');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 1MB!');
            }
            this.loginQrCode.imageUrl = URL.createObjectURL(file);
            this.loginQrCode.fileSource = file
            return false;
        },
        // 手动扫码上传图片 *******结束********

        //  处理 云机界面 粘贴图片上传扫码
        async handlePaste(index, e) {
            // 阻止默认粘贴行为
            e.preventDefault();

            // 检查剪贴板数据
            if (!e.clipboardData || !e.clipboardData.items) {
                this.$message.warning('剪贴板数据不可用');
                return;
            }

            const items = e.clipboardData.items;
            let foundImage = false;


            // 遍历剪贴板项目
            for (let i = 0; i < items.length; i++) {
                const item = items[i];
                // 检查是否为图片文件
                if (item.kind === 'file' && item.type.match(/^image\//)) {
                    foundImage = true;

                    try {
                        const file = item.getAsFile();
                        console.log(file, 'filefile')
                        // 检查文件大小
                        if (file.size > 1 * 1024 * 1024) {
                            this.$message.error('图片不能超过1MB');
                            return;
                        }

                        // 获取当前实例信息
                        const tenant = this.yunjiTable[index];
                        if (!tenant || !tenant.wss_url) {
                            this.$message.error('请先连接云控');
                            return;
                        }

                        if (tenant.onlineStatus !== 2) {
                            this.$message.warning('账号请先确认登录');
                            return;
                        }

                        try {
                            // 创建FormData
                            const form = new FormData();
                            form.append('file', file);
                            form.append('accountId', tenant.accountId);

                            // 调用iframe组件的扫码方法
                            const iframeRef = this.$refs[`yunjiIframeRef_${index}`];
                            console.log(iframeRef, iframeRef[0], 'iframeRef')
                            if (iframeRef && iframeRef[0]) {
                                const result = await iframeRef[0].onScanDrop('copy', form);

                                if (result && result.code === 200) {
                                    tenant.wss_url = ''
                                    this.$message.success('自动上号成功');
                                } else {
                                     tenant.wss_url = ''
                                    // this.$message.error(result?.message || '上传或写入失败');
                                }
                            } else {
                                this.$message.error('云控组件未就绪');
                            }
                        } finally {
                            // loading.close();
                        }

                    } catch (error) {
                        console.error('处理粘贴图片失败:', error);
                        // this.$message.error('处理图片失败: ' + error.message);
                    }

                    break;
                }
            }

            if (!foundImage) {
                this.$message.warning('剪贴板内容不是图片，请复制图片后重试');
            }
        },
        async onScanDrop(index, e) {
            e.preventDefault();
            // 获取当前实例信息
            const tenant = this.yunjiTable[index];
            if (!tenant || !tenant.wss_url) {
                this.$message.error('请先连接云控');
                return;
            }

            if (tenant.onlineStatus !== 2) {
                this.$message.warning('账号请先确认登录');
                return;
            }
            const files = e.dataTransfer && e.dataTransfer.files;
            if (!files || !files.length) {
                this.$message.warning('未检测到图片文件');
                return;
            }
            const file = files[0];
            if (!/^image\/(png|jpeg|jpg)$/.test(file.type)) {
                this.$message.error('仅支持PNG/JPEG图片');
                return;
            }
            if (file.size > 1 * 1024 * 1024) {
                this.$message.error('图片不能超过1MB');
                return;
            }

            try {
                const form = new FormData();
                form.append('file', file);
                form.append('accountId', tenant.accountId);

                // 调用 iframe 组件的扫码方法
                const iframeRef = this.$refs[`yunjiIframeRef_${index}`];
                if (iframeRef && iframeRef[0] && typeof iframeRef[0].onScanDrop === 'function') {
                    const result = await iframeRef[0].onScanDrop('copy', form);
                    if (result && result.code === 200) {
                          tenant.wss_url = ''
                        this.$message.success('自动上号成功');
                    } else {
                         tenant.wss_url = ''
                        // this.$message.error(result?.message || '上传或写入失败');
                    }
                } else {
                    this.$message.error('云控组件未就绪');
                }
            } catch (error) {
                // this.$message.error('处理图片失败: ' + error.message);
            }
        },
        getList(type) {
            this.loading = true;
            let data = {
                pageNum: 1,
                pageSize: 100
            }
                tenantLists(data)
                    .then(res => {
                        if (res.code === 200 && res.rows) {
                            this.yunjiTable = res.rows.map(item => ({
                                ...item,
                                wss_url: '',
                                sessionId: '',
                                accountId: item.id,
                                onlineStatus:item.onlineStatus,
                                timer: null
                            }));
                        }
                    })
                    .finally(() => {
                        this.loading = false;
                    });
        },


        getDay(val) {
            if (!val) {
                return '0天'
            }
            const now = new Date();
            const start = new Date(val);
            if (isNaN(start.getTime())) return '0天0小时';
            // 计算时间差（毫秒）
            const timeDiff = now.getTime() - start.getTime();
            if (timeDiff <= 0) return '0天0小时';
            const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
            const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            return `${days}天${hours}小时`;
        },
        remoteMethod(query) {
            this.throttledRemoteMethod(query);
        },
        // 实际处理搜索的方法
        async handleRemoteSearch(query) {
            // 如果搜索词为空，清空选项
            if (!query) {
                this.options = [];
                return;
            }
            try {
                this.formData.account = query
                // 显示加载状态
                this.loading2 = true;
                const res = await getAllList(this.formData)
                if (res.code == 200 && res.rows.length > 0) {
                    this.options = res.rows
                }
            } catch (error) {
                this.options = []; 
            } finally {
                this.loading2 = false;
            }
        },
        // 为指定实例重新连接
        reconts(tenant, index) {
            if (tenant.wss_url) {
                tenant.wss_url = '';
                let data = {
                    id: tenant.id
                };
                openAccount(data).then(res => {
                    if (res.code === 200) {
                        tenant.wss_url = res.data.wssUrl;
                        tenant.sessionId = res.data.sessionId;
                        tenant.accountId = res.data.accountId;

                        // 清除旧定时器
                        if (tenant.timer) {
                            clearTimeout(tenant.timer);
                        }

                        // 设置新定时器
                        tenant.timer = setTimeout(() => {
                            tenant.wss_url = '';
                            this.$message.info(`账号 ${tenant.account} 连接已超时，请重新打开`);
                        }, 5 * 60 * 1000);
                    }
                });
            }
        },
        activateComponent(tenant, index) {
              //重新计算到过期时间
            if (tenant.timer) {
                clearTimeout(tenant.timer);
                tenant.timer = null;
            }

            // 设置5分钟后自动清空wss_url的定时器
            tenant.timer = setTimeout(() => {
                tenant.wss_url = '';
                this.$message.warning(`账号 ${tenant.account} 连接已超时，请重新打开`);
            }, 5 * 60 * 1000);
        },
        openRentDialog() {
            if (this.yunjiTable.some(item => item.wss_url)) {
                this.$modal
                    .confirm(
                        `检测到当前有云控打开,请先确认登录,避免账号失效`,
                        '提示',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    )
                    .then(() => {
                        // 用户点击确定：加载列表
                        this.$emit('openRentDialog')
                    })
                    .catch(() => {
                        this.$emit('openRentDialog')
                    });
            } else {
                this.$emit('openRentDialog')
            }
        },
        accountCreate() {
            this.loading1 = true;
            if(this.yunjiForm.account){
                this.yunjiForm.account = this.yunjiForm.account.trim()
            }else{
                return this.$message.warning('请输入QQ账号！');
            }
            addQ(this.yunjiForm).then(res => {
                if (res.code === 200) {
                    this.$message.success(res.msg);
                    this.dataType = 1; // 确认类型(1创建 2打开)

                    // 查找第一个未被占用且未被分配的实例
                    let instanceIndex = this.yunjiTable.findIndex((item, index) => 
                        !item.wss_url && !this.assigningInstances.has(index));

                    if (instanceIndex !== -1) {
                        // 标记该实例正在被分配
                        this.assigningInstances.add(instanceIndex);
                        
                        // 更新实例信息
                        Object.assign(this.yunjiTable[instanceIndex], {
                            id: res.data.accountId,
                            account: this.yunjiForm.account,
                            loginType: this.yunjiForm.loginType,
                            machineType: this.yunjiForm.machineType,
                            onlineStatus: 1,
                            loginTime: new Date().toISOString(),
                            createDays: new Date().toISOString(),
                            createdTime: new Date().toLocaleString()
                        });

                        // 设置连接信息
                        this.openUrlForInstance(this.yunjiTable[instanceIndex], res.data);
                        
                        // 在连接建立后取消标记
                        this.$nextTick(() => {
                            this.assigningInstances.delete(instanceIndex);
                        });
                    } else {
                        // 所有实例都已连接，提示用户
                        this.$message.warning('所有云控都已连接，请先关闭一个再尝试创建新账号');
                    }
                }
            }).catch(error => {
                this.$message.error('创建账号失败，请重试');
                console.error('创建账号失败:', error);
            }).finally(() => {
                this.loading1 = false;
            });
        },
        // 从父组件调用，为指定实例打开连接
        openUrlForInstanceFromParent(data, type) {
            console.log('从父组件调用，为指定实例打开连接', data, type);
            this.dataType = 2
            // 查找是否已存在相同ID的实例
            let instanceIndex = this.yunjiTable.findIndex(item => item.id === data.id);

            if (instanceIndex !== -1) {
                // 找到对应实例，直接更新
                this.openUrlForInstance(this.yunjiTable[instanceIndex], data, type);
            } else {
                // 找不到对应实例，找到第一个未连接且未被分配的实例
                instanceIndex = this.yunjiTable.findIndex((item, index) => 
                    !item.wss_url && !this.assigningInstances.has(index));

                if (instanceIndex !== -1) {
                    // 标记该实例正在被分配
                    this.assigningInstances.add(instanceIndex);
                    
                    // 更新实例信息
                    Object.assign(this.yunjiTable[instanceIndex], {
                        id: data.id,
                        account: data.account,
                        loginType: data.loginType,
                        machineType: data.machineType,
                        onlineStatus: data.onlineStatus,
                        loginTime: data.loginTime,
                        createDays: data.createDays,
                        createdTime: data.createdTime
                    });
                    console.log('更新实例信息', this.yunjiTable[instanceIndex]);
                    this.openUrlForInstance(this.yunjiTable[instanceIndex], data, type);
                    
                    // 在连接建立后取消标记
                    this.$nextTick(() => {
                        this.assigningInstances.delete(instanceIndex);
                    });
                } else {
                    // 所有实例都已连接，提示用户
                    this.$message.warning('所有云控都已连接，请先关闭一个再尝试');
                }
            }
        },
        // 为指定实例打开连接
        openUrlForInstance(tenant, data, type) {
            if (type === 'see') {
                tenant.account = data.account;
            }
            tenant.sessionId = data.sessionId;
            tenant.wss_url = data.wss_url;
            tenant.accountId = data.accountId;
            if(data.onlineStatus) {
                 tenant.onlineStatus = data.onlineStatus;
            }
            
           
            // 清除可能存在的旧定时器
            if (tenant.timer) {
                clearTimeout(tenant.timer);
                tenant.timer = null;
            }

            // 设置5分钟后自动清空wss_url的定时器
            tenant.timer = setTimeout(() => {
                tenant.wss_url = '';
                this.$message.warning(`账号 ${tenant.account} 连接已超时，请重新打开`);
            }, 5 * 60 * 1000);
        },

        async openAccountUrl() {
            try {
                if(!this.selectId){
                    this.$message.warning('请选择一个账号')
                    return
                }
                this.loading3 = true
                this.dataType = 2
                const res = await openAccount({ id: this.selectId });

                if (res.code === 200) {
                    this.loading3 = false;
                    let datas = {
                        sessionId: res.data.sessionId,
                        wss_url: res.data.wssUrl,
                        accountId: res.data.accountId
                    };
                 
                    // 找到对应的实例并更新
                    let instanceIndex = this.yunjiTable.findIndex(item => item.id === this.selectId);

                    if (instanceIndex !== -1) {
                        const option = this.options.find(opt => opt.id === this.selectId);
                        if (option) {
                            this.yunjiTable[instanceIndex].onlineStatus = option.onlineStatus;
                            this.yunjiTable[instanceIndex].account = option.account;
                            // 其它字段也可同步
                        }

                        // 找到对应实例，直接更新
                        this.openUrlForInstance(this.yunjiTable[instanceIndex], datas);
                    } else {
                        // 找不到对应实例，找到第一个未连接且未被分配的实例
                        instanceIndex = this.yunjiTable.findIndex((item, index) => 
                            !item.wss_url && !this.assigningInstances.has(index));

                        if (instanceIndex !== -1) {
                            // 标记该实例正在被分配
                            this.assigningInstances.add(instanceIndex);
                            
                            // 更新实例信息
                            const option = this.options.find(opt => opt.id === this.selectId);
                            if (option) {
                                this.yunjiTable[instanceIndex].id = this.selectId;
                                this.yunjiTable[instanceIndex].account = option.account;
                                this.yunjiTable[instanceIndex].onlineStatus = option.onlineStatus;
                            }
                            
                            this.openUrlForInstance(this.yunjiTable[instanceIndex], datas);
                            
                            // 在连接建立后取消标记
                            this.$nextTick(() => {
                                this.assigningInstances.delete(instanceIndex);
                            });
                        } else {
                            // 所有实例都已连接，提示用户
                            this.$message.warning('所有云控都已连接，请先关闭一个再尝试');
                        }
                    }
                }
            } catch (error) {
                this.loading3 = false;
                this.$message.error('打开账号失败，请重试');
            }
        },
        // 复制指定账号
        copyAccount(tenant) {
            this.$copyText(tenant.account).then(() => {
                this.$message.success(`已复制账号 ${tenant.account} 到剪切板`);
            });
        },
        // 为指定实例处理登录失败
        loginErrSure(tenant, index) {
            this.$modal.confirm(`此账号 ${tenant.account} 确定登录失败吗?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                yunjilogin(tenant.sessionId, this.dataType, tenant.accountId, 1).then(res => {
                    if (tenant.timer) {
                        clearTimeout(tenant.timer);
                        tenant.timer = null;
                    }
                    tenant.wss_url = '';
                    tenant.onlineStatus = 1; // 登录失败，设为异常/失败状态
                    if (res.code === 200) {
                        linkClose(tenant.accountId);
                         this.options  = []
                             this.selectId = ''
                         this.$nextTick(() => {
                            this.$refs.remoteSelect.$forceUpdate();
                          });
                    }
                    this.$message.success(res.msg);
                });
            });
        },
        // 刷新所有实例
        // fresh() {
        //     this.getList();
        // },
        // 为指定实例处理确认登录
        handleSubmit(tenant, index) {
            this.$modal.confirm(`在确认登录之前,请检查账号 ${tenant.account} 是否登录成功`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                yunjilogin(tenant.sessionId, this.dataType, tenant.accountId, 2).then(res => {
                    tenant.wss_url = '';
                    if (tenant.timer) {
                        clearTimeout(tenant.timer);
                        tenant.timer = null;
                    }
                    if (res.code === 200) {
                        this.yunjiForm.account = ''
                        this.$message.success(res.msg);
                        linkClose(tenant.accountId);

                       this.options  = []
                               this.selectId = ''
                        this.$nextTick(() => {
                            
                            this.$refs.remoteSelect.$forceUpdate(); // 关键：清空组件内部缓存
                             
                        });
                    }
                }).catch(() => {
                    this.loading = false;
                });
            }).catch(() => {
                this.$modal.msg("取消登录");
            });
        },
        // 为指定实例删除账号
        async deleteSure(tenant, index) {
            this.$modal.confirm(`确定要删除账号 ${tenant.account} 吗?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let data = {
                    id: tenant.accountId,
                };
                delAccount(data).then(res => {
                    if (tenant.timer) {
                        clearTimeout(tenant.timer);
                        tenant.timer = null;
                    }
                    tenant.wss_url = '';
                    if (res.code === 200) {
                        this.$message.success('账号删除成功');
                          this.options  = []
                            this.selectId = ''
                        this.$nextTick(() => {
                           
                            this.$refs.remoteSelect.$forceUpdate(); // 关键：清空组件内部缓存
                          
                        });
                    }
                });
            });
        },
        // 为指定实例截图或扫码
        takeAndDownloadScreenshot(type, index) {
            const tenant = this.yunjiTable[index];
            if (!tenant.wss_url) {
                this.$message.warning('请先连接云控');
                return;
            }
            this.$nextTick(() => {
                const iframeRef = this.$refs[`yunjiIframeRef_${index}`];
                if (iframeRef && iframeRef[0]) {
                    if (type === 'jietu') {
                        iframeRef[0].takeAndDownloadScreenshot();
                    } else {
                        if (tenant.onlineStatus != 2) {
                            this.$message.warning('账号请先确认登录')
                            return
                        }
                        iframeRef[0].triggerScanUpload('scan');
                    }
                }
            });
        },
        // 为指定实例扫码上号
        scanClick(type, index) {
            const tenant = this.yunjiTable[index];
            console.log(tenant,888)
            if (tenant.onlineStatus != 2) {
                this.$message.warning('账号请先确认登录')
                return
            }
            this.$nextTick(() => {
                const iframeRef = this.$refs[`yunjiIframeRef_${index}`];
                if (iframeRef && iframeRef[0]) {
                    iframeRef[0].triggerScanUpload('scanAuto');
                }
            });
        },
        closeYunji(tenant,index) {
            //   this.$modal.confirm(`确定要关闭账号 ${tenant.account} 吗?`, '提示', {
            //     confirmButtonText: '确定',
            //     cancelButtonText: '取消',
            //     type: 'warning'
            // }).then(() => {
                yunjiClose(tenant.id).then(res => { 
                    if (tenant.timer) {
                        clearTimeout(tenant.timer);
                        tenant.timer = null;
                    }
                    tenant.wss_url = '';
                     if (res.code === 200) {
                        linkClose(tenant.accountId);
                        this.$message.success('账号关闭成功');
                          this.options  = []
                            this.selectId = ''
                        this.$nextTick(() => {
                            this.$refs.remoteSelect.$forceUpdate(); // 关键：清空组件内部缓存
                        });
                     }
                });
            // })
        }
    },
    mounted() {
        this.getList()
    },
    created() {

    },
    beforeDestroy() {
        // 组件销毁前取消节流函数，防止内存泄漏
        this.throttledRemoteMethod.cancel();

        // 清除所有实例的定时器
        this.yunjiTable.forEach(tenant => {
            if (tenant.timer) {
                clearTimeout(tenant.timer);
                tenant.timer = null;
            }
        });

        // 清除单个实例的定时器
        if (this.wssUrlTimer) {
            clearTimeout(this.wssUrlTimer);
            this.wssUrlTimer = null;
        }
        
        // 清除实例分配跟踪
        this.assigningInstances.clear();
    }

};


</script>
<style scoped lang="scss">
.margin-left-10 {
    margin-left: 10px;
}

// 多个云机实例容器样式
.grid-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-top: 10px;
}

.grid-box {
    position: relative;
    flex: 0 0 auto;
}

// .grid-content {
//     position: relative;
//     cursor: pointer;
//     // width: 100%;
//     width: 334px;
//     padding: 200px 0;
//     // height: calc(100vh - 300px);
//     box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0.8px;
//     border-radius: 18px;
//     display: flex;
//     flex-direction: column;

//     &:hover {
//         box-shadow: rgba(0, 0, 0, 0.4) 0px 3px 12px 0px;
//     }
// }

.flex-l {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
}

.yunji-img {
    object-fit: contain;
}

.add-btn {
    background: linear-gradient(90deg, #6C5DD3, #9991d2);
}

::v-deep {
    .el-radio {
        margin-right: 10px;
    }
}

.flex-footer {
    padding-top: 10px;
    position: relative;

    .flexc {
        display: flex;
        justify-content: center;
        width: 334px;
        padding-bottom: 10px;

        .margin-left-10 {
            margin-left: 5px;
        }
    }

    &::before {
        content: "";
        position: absolute;
        top: 0;
        left: 50%;
        transform: translate(-50%);
        width: 6.2813vw;
        height: .25vh;
        background: #000;
        z-index: 1;
        transition: background .3s ease;
        border-radius: .9259vh;
    }
}

.tips {
    cursor: pointer;

    div {
        font-size: 12px;
        line-height: 1.6;
        padding: 2px 5px;

        &:hover {
            color: #fff;
            background: #6C5DD3;
            border-radius: 4px;

        }
    }
}

.option-content {
    color: #333;
    display: flex;
    align-items: center;
}


.margin-left-5 {
    margin-left: 5px;
}

.account-tips {
    position: absolute;
    z-index: 99;
    width: 100%;
    text-align: center;
    cursor: pointer;
}

.grid-box {
    position: relative;
}

.flex-r-tips-1 {
    margin-left: 22px;

    .accounts {
        color: #6C5DD3;
    }
}

.el-icon-question {
    color: #6C5DD3;
    font-size: 20px;
    position: absolute;
    right: -7px;
    top: -4px;
    z-index: 100;
    border-radius: 50%;
    background: #fff;
}

.paste-input {
      position: absolute;
    top: 15px;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 10;
    opacity: 0.6;
    cursor: pointer;
    border: none;
    outline: none;
    background: transparent;
    width: 50%;
    height: 50px;
    margin-left: -16%;
    left: 50%;
    color: #333;
}


.grid-content {
    position: relative;
    cursor: pointer;
    width: 334px;
    height: 620px;
    box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0.8px;
    border-radius: 18px;
    display: flex;
    flex-direction: column;
    &:hover {
        box-shadow: rgba(0, 0, 0, 0.4) 0px 3px 12px 0px;
        .paste-input {
            opacity: 0.8;
            background: rgba(108, 93, 211, 0.1);
        }
    }
}

.paste-focus {
    background: #897ddc;
    color: #FFFFFF;
  }

  .paste-container {
    margin: 30px 0 30px;
    padding: 20px 20px;
    border-radius: 8px;
    cursor: pointer;
    width: 100%;
    height: 150px;
    border: 1px #999999 dashed;

    &:hover {
      border-color: #897ddc;
    }
  }
.login-uploader{
    display: flex;
    justify-content: center;
}
</style>
